package com.web.controoller;

import com.web.pojo.domain.Device;
import com.web.pojo.domain.DeviceGroup;
import com.web.pojo.dto.*;
import com.web.pojo.vo.CommonResult;
import com.web.service.DeviceGroupServer;
import com.web.service.DeviceServer;
import com.web.service.NetworkServer;
import com.web.utils.DownLinkDataUtil;
import com.web.utils.SecurityUtils;
import com.web.utils.ToolUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: wws
 * @Date: 2021/1/12 15:57
 * describe:
 */
@CrossOrigin
@RequestMapping("/deviceGroup")
@RestController
public class DeviceGroupController {

    @Autowired
    DeviceGroupServer deviceGroupServer;

    @Autowired
    DeviceServer deviceServer;

    @Autowired
    NetworkServer networkServer;


    @PostMapping("/insert")
    @ApiOperation("添加设备组")
    public CommonResult insertDeviceGroup(@RequestBody DeviceGroup deviceGroup) {
        System.out.println(deviceGroup);
        deviceGroup.setCreateBy(SecurityUtils.getUsername());
        return CommonResult.insert(deviceGroupServer.insertDeviceGroup(deviceGroup));
    }

    @PostMapping("/update")
    @ApiOperation("修改设备组")
    public CommonResult updateDeviceGroup(@RequestBody DeviceGroup deviceGroup) {
        deviceGroup.setUpdateBy(SecurityUtils.getUsername());
        return CommonResult.update(deviceGroupServer.updateDeviceGroup(deviceGroup));
    }

    @PostMapping("/delete")
    @ApiOperation("删除设备组")
    public CommonResult deleteDeviceGroup(@RequestBody List<Integer> deviceGroupIds) {
        String username = SecurityUtils.getUsername();
        return CommonResult.delete(deviceGroupServer.deleteDeviceGroup(username, deviceGroupIds));
    }

    @PostMapping("/selectList")
    @ApiOperation("查看设备组")
    public CommonResult selectDeviceGroupList(@RequestBody(required = false) String str) {
        Integer userId = SecurityUtils.getUserId();
        List<DeviceGroup> list = deviceGroupServer.selectDeviceGroupList(str, userId);
        return CommonResult.select(list);
    }

    @PostMapping("/selectDeviceNotInGroup")
    @ApiOperation("查看不在组的中设备")
    public CommonResult selectDeviceNotInGroup(@RequestBody Integer groupId) {
        Integer userId = SecurityUtils.getUserId();
        List<Device> list = deviceGroupServer.selectDeviceNotInGroup(userId, groupId);
        return CommonResult.select(list);
    }

    @PostMapping("/deviceGroupAddDevice")
    @ApiOperation("往设备组中添加设备")
    public CommonResult deviceGroupAddDevice(@RequestBody DeviceGroupAddDeviceDTO dto) {
        DeviceGroup deviceGroup = deviceGroupServer.selectDeviceGroupById(dto.getDeviceGroupId());
        if (deviceGroup == null) {
            return CommonResult.error("设备组不存在");
        }
        List<Device> deviceList = deviceServer.selectDeviceListByIds(dto.getDeviceIds());
        System.out.println(deviceList);
        byte[] FRMPayload = DownLinkDataUtil.deviceGroupAddDevice(ToolUtil.toByteArray(deviceGroup.getDeviceGroupAppkey()), ToolUtil.toByteArray(deviceGroup.getDeviceGroupAddr()), deviceList);
        byte[] downPayload = DownLinkDataUtil.generateGroupDownPayload(FRMPayload);
        Set<String> gateWaySet = getGateWayEuiSet(deviceList);
        System.out.println(gateWaySet);
        SendAddGroupMsg(downPayload, gateWaySet);
        deviceGroupServer.deviceGroupAddDevice(dto);
        return CommonResult.success("操作完成");
    }

    private void SendAddGroupMsg(byte[] downPayload, Set<String> gateWaySet) {
        for (String s : gateWaySet) {
            byte[] token = ToolUtil.CalAppNonce(2);
            byte[] downData = DownLinkDataUtil.DeviceGroupCommands(token, ToolUtil.toByteArray(s), downPayload);
            networkServer.downstreamData(downData);
        }
    }

    private Set<String> getGateWayEuiSet(List<Device> deviceList) {
        Set<String> gateWaySet = new HashSet<>();
        for (Device device : deviceList) {
            gateWaySet.add(device.getDeviceBindGateway());
        }
        return gateWaySet;
    }


    @PostMapping("/setSwitchGroupState")
    @ApiOperation("设置开关组操作")
    public CommonResult setSwitchGroupState(@RequestBody SetSwitchStateDTO dto) {
        DeviceGroup deviceGroup = deviceGroupServer.selectDeviceGroupById(dto.getId());
        if (deviceGroup == null) {
            return CommonResult.error("设备组不存在");
        }
        List<Device> deviceList = deviceGroupServer.selectDeviceListByGroupId(deviceGroup.getDeviceGroupId());
        Set<String> gateWaySet = getGateWayEuiSet(deviceList);
        byte[] FRMPayload = DownLinkDataUtil.setDeviceGroupSwitchStatePayLoad(dto.getDeviceChannelParameter1(), dto.getDeviceChannelParameter2());
        System.out.println(deviceGroup);
        byte[] downPayload = DownLinkDataUtil.generateGroupDownPayload(deviceGroup, FRMPayload);
        SendAddGroupMsg(downPayload, gateWaySet);
        return CommonResult.success("已发送");
    }


    @PostMapping("/setSwitchGroupControlState")
    @ApiOperation("组设置定时开关时间表")
    public CommonResult setSwitchGroupControlState(@RequestBody SetSwitchScheduleDTO dto) {
        DeviceGroup deviceGroup = deviceGroupServer.selectDeviceGroupById(dto.getId());
        if (deviceGroup == null) {
            return CommonResult.error("设备组不存在");
        }
        List<Device> deviceList = deviceGroupServer.selectDeviceListByGroupId(deviceGroup.getDeviceGroupId());
        Set<String> gateWaySet = getGateWayEuiSet(deviceList);
        byte[] FRMPayload = DownLinkDataUtil.deviceGroupSwitchControlSchedulePayLoad(dto);
        byte[] downPayload = DownLinkDataUtil.generateGroupDownPayload(deviceGroup, FRMPayload);
        SendAddGroupMsg(downPayload, gateWaySet);
        return CommonResult.success("已发送");
    }

    @PostMapping("/setSwitchGroupControl")
    @ApiOperation("组设置手动、远程、定时开关控制")
    public CommonResult setSwitchGroupControl(@RequestBody SetSwitchControlStateDTO dto) {
        DeviceGroup deviceGroup = deviceGroupServer.selectDeviceGroupById(dto.getId());
        if (deviceGroup == null) {
            return CommonResult.error("设备组不存在");
        }
        List<Device> deviceList = deviceGroupServer.selectDeviceListByGroupId(deviceGroup.getDeviceGroupId());
        Set<String> gateWaySet = getGateWayEuiSet(deviceList);
        byte[] FRMPayload = DownLinkDataUtil.setDeviceGroupSwitchControlStatePayLoad(dto);
        byte[] downPayload = DownLinkDataUtil.generateGroupDownPayload(deviceGroup, FRMPayload);
        SendAddGroupMsg(downPayload, gateWaySet);
        return CommonResult.success("已发送");
    }


    @PostMapping("/setSwitchGroupDimmingLevel")
    @ApiOperation("组设置调光等级")
    public CommonResult setSwitchGroupControl(@RequestBody SetSwitchDimmingLevelDTO dto) {
        DeviceGroup deviceGroup = deviceGroupServer.selectDeviceGroupById(dto.getId());
        if (deviceGroup == null) {
            return CommonResult.error("设备组不存在");
        }
        List<Device> deviceList = deviceGroupServer.selectDeviceListByGroupId(deviceGroup.getDeviceGroupId());
        Set<String> gateWaySet = getGateWayEuiSet(deviceList);
        byte[] FRMPayload = DownLinkDataUtil.setDeviceGroupSwitchDimmingLevelPayLoad(dto.getDeviceChannelParameter1(), dto.getDeviceChannelParameter2());
        byte[] downPayload = DownLinkDataUtil.generateGroupDownPayload(deviceGroup, FRMPayload);
        SendAddGroupMsg(downPayload, gateWaySet);
        return CommonResult.success("已发送");
    }

    @PostMapping("/setSwitchGroupReportingPeriod")
    @ApiOperation("组设置上报周期")
    public CommonResult setSwitchGroupReportingPeriod(@RequestBody SetSwitchReportingPeriodDTO dto) {
        DeviceGroup deviceGroup = deviceGroupServer.selectDeviceGroupById(dto.getId());
        if (deviceGroup == null) {
            return CommonResult.error("设备组不存在");
        }
        List<Device> deviceList = deviceGroupServer.selectDeviceListByGroupId(deviceGroup.getDeviceGroupId());
        Set<String> gateWaySet = getGateWayEuiSet(deviceList);
        byte[] FRMPayload = DownLinkDataUtil.setDeviceGroupSwitchReportingPeriod(dto.getReportHour(), dto.getReportMinute());
        byte[] downPayload = DownLinkDataUtil.generateGroupDownPayload(deviceGroup, FRMPayload);
        SendAddGroupMsg(downPayload, gateWaySet);
        return CommonResult.success("已发送");
    }

    @PostMapping("/setGroupAppKey")
    @ApiOperation("组设置APPKEY")
    public CommonResult setGroupAppKey(@RequestBody SetSwitchAppKeyDTO dto) {
        DeviceGroup deviceGroup = deviceGroupServer.selectDeviceGroupById(dto.getId());
        if (deviceGroup == null) {
            return CommonResult.error("设备组不存在");
        }
        List<Device> deviceList = deviceGroupServer.selectDeviceListByGroupId(deviceGroup.getDeviceGroupId());
        Set<String> gateWaySet = getGateWayEuiSet(deviceList);
        byte[] FRMPayload = DownLinkDataUtil.setDeviceGroupSwitchAppKey(ToolUtil.toByteArray(dto.getAppkey()));
        byte[] downPayload = DownLinkDataUtil.generateGroupDownPayload(deviceGroup, FRMPayload);
        SendAddGroupMsg(downPayload, gateWaySet);
        return CommonResult.success("已发送");
    }

    @PostMapping("/setGroupReboot")
    @ApiOperation("组重启")
    public CommonResult setGroupReboot(@RequestBody Integer groupId) {
        DeviceGroup deviceGroup = deviceGroupServer.selectDeviceGroupById(groupId);
        if (deviceGroup == null) {
            return CommonResult.error("设备组不存在");
        }
        List<Device> deviceList = deviceGroupServer.selectDeviceListByGroupId(deviceGroup.getDeviceGroupId());
        Set<String> gateWaySet = getGateWayEuiSet(deviceList);
        byte[] FRMPayload = DownLinkDataUtil.setDeviceGroupSwitchReboot();
        byte[] downPayload = DownLinkDataUtil.generateGroupDownPayload(deviceGroup, FRMPayload);
        SendAddGroupMsg(downPayload, gateWaySet);
        return CommonResult.success("已发送");
    }

    @PostMapping("/setGroupReset")
    @ApiOperation("组恢复默认设置")
    public CommonResult setGroupReset(@RequestBody Integer groupId) {
        DeviceGroup deviceGroup = deviceGroupServer.selectDeviceGroupById(groupId);
        if (deviceGroup == null) {
            return CommonResult.error("设备组不存在");
        }
        List<Device> deviceList = deviceGroupServer.selectDeviceListByGroupId(deviceGroup.getDeviceGroupId());
        Set<String> gateWaySet = getGateWayEuiSet(deviceList);
        byte[] FRMPayload = DownLinkDataUtil.setDeviceGroupSwitchReset();
        byte[] downPayload = DownLinkDataUtil.generateGroupDownPayload(deviceGroup, FRMPayload);
        SendAddGroupMsg(downPayload, gateWaySet);
        return CommonResult.success("已发送");
    }

    @PostMapping("/setGroupTime")
    @ApiOperation("组设置设备时间")
    public CommonResult setGroupTime(@RequestBody SetDeviceTimeDTO dto) {
        DeviceGroup deviceGroup = deviceGroupServer.selectDeviceGroupById(dto.getId());
        if (deviceGroup == null) {
            return CommonResult.error("设备组不存在");
        }
        List<Device> deviceList = deviceGroupServer.selectDeviceListByGroupId(deviceGroup.getDeviceGroupId());
        Set<String> gateWaySet = getGateWayEuiSet(deviceList);
        byte[] FRMPayload = DownLinkDataUtil.setDeviceGroupSwitchTime(dto.getDay(), dto.getMonth(), dto.getYear(), dto.getSecond(), dto.getMinute(), dto.getHour());
        byte[] downPayload = DownLinkDataUtil.generateGroupDownPayload(deviceGroup, FRMPayload);
        SendAddGroupMsg(downPayload, gateWaySet);
        return CommonResult.success("已发送");
    }
}
